package com.nhc.activity_fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.astrob.activitys.AppContext;
import com.astrob.model.LonLat;
import com.astrob.model.Msg;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.astrob.view.BaseViewHolder;
import com.nhc.database.dbmodel.WayPoint;
import com.nhc.database.manager.DBDataCenter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.base.BaseAdapter;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.model.Entry;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.AlertDialog.OnDialogButtonClickListener;
import zuo.biao.library.ui.EditTextInfoActivity;
import zuo.biao.library.ui.EditTextInfoWindow;
import zuo.biao.library.ui.PageScroller;
import zuo.biao.library.ui.TopMenuWindow;
import zuo.biao.library.util.StringUtil;

public class NaviPtActivity extends BaseActivity implements OnDialogButtonClickListener, TimeRefresher.OnTimeRefreshListener {
    private final String TAG = "NaviPtActivity";

    //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, NaviPtActivity.class);
    }
    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.navipt_activity);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>
    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private ListView lv_navipt;
    private Button bt_navipt_do;
    private Button bt_navipt_selectall;
    private Button bt_navipt_selectallno;

    //示例代码>>>>>>>>
    @Override
    public void initView() {//必须在onCreate方法内调用
        autoSetTitle();//自动设置标题为上个Activity传入的INTENT_TITLE

        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        lv_navipt = (ListView) findViewById(R.id.lv_navipt);
        bt_navipt_do = (Button) findViewById(R.id.bt_navipt_do);
        bt_navipt_selectall = (Button) findViewById(R.id.bt_navipt_selectall);
        bt_navipt_selectallno = (Button) findViewById(R.id.bt_navipt_selectallno);
        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }

    //示例代码<<<<<<<<
    private DemoAdapter adapter;
    //示例代码>>>>>>>>

    /**
     * 示例方法 ：显示列表内容
     *
     * @param list
     */
    private void setList(List<Entry<Integer, String>> list) {
        if (adapter == null) {
            adapter = new DemoAdapter(context);
            lv_navipt.setAdapter(adapter);
        }
        adapter.refresh(list);
    }
    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private List<Entry<Integer, String>> naviptlist;
    private ArrayList<WayPoint> mNaviptList = new ArrayList<WayPoint>();
    private boolean mIsEdit = false;//选择删除
    private HashMap<Integer, Boolean> hashMap;

    private boolean getItemChecked(int position) {
        return hashMap.get(position);
    }

    private void setItemChecked(int position, boolean isChecked) {
        if (adapter != null) {
            hashMap.put(position, isChecked);
            adapter.notifyDataSetChanged();
        }
    }

    //排序方式
    int _order = 0;//0-id 时间 1-name 2-距离
    int _iconIndex = -1;//按图标查找

    private void resetWayPoint() {
        if (mKey.length() > 0) {
            LonLat carLL = SysUtils.getInstance().getLL();
            mNaviptList = DBDataCenter.getInstance().searchWaypt(mKey, carLL, true);
            mKey = "";
        } else if (_iconIndex >= 0) {
            mNaviptList = DBDataCenter.getInstance().searchWayptByIcon(_iconIndex);
            _iconIndex = -1;
        } else {
            mNaviptList = DBDataCenter.getInstance().getWaypointListByOrder(_order);
        }
    }

    //示例代码>>>>>>>>>
    boolean _isWorking = false;

    @Override
    public void initData() {//必须在onCreate方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        if (_isWorking) {
            return;
        }

        _isWorking = true;
        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                resetWayPoint();
                naviptlist = getList();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        setList(naviptlist);
                        _isWorking = false;
                    }
                });
            }
        });
        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }

    protected List<Entry<Integer, String>> getList() {
        naviptlist = new ArrayList<Entry<Integer, String>>();
        for (int i = 0; i < mNaviptList.size(); i++) {
            naviptlist.add(new Entry<Integer, String>(i, ""));
        }
        return naviptlist;
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreate方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<
        lv_navipt.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                setResult(RESULT_OK, new Intent().putExtra(RESULT_CLICKED_ITEM, position));
//                finish();
                if (mIsEdit && null != hashMap) {
                    boolean isSelected = hashMap.get(position);
                    hashMap.put(position, !isSelected);
                    if (adapter != null) {
                        adapter.notifyDataSetChanged();
                    }

                    boolean haveselected = false;
                    for (int i = 0; i < mNaviptList.size(); i++) {
                        if (hashMap.get(i)) {
                            haveselected = true;
                            break;
                        }
                    }
                    if (haveselected) {
                        bt_navipt_do.setText(getString(R.string.delete));
                    } else {
                        bt_navipt_do.setText(getString(R.string.cancel));
                    }

                } else if (position < mNaviptList.size()) {
                    DBDataCenter.getInstance().makerEdit = mNaviptList.get(position);
                    toActivity(MarkerPointActivity.createIntent(getBaseContext(), false, true), REQUEST_DETAIL);
                }
            }
        });

        //分页滚动示例代码<<<<<<<<<<<<<<<<<<<
        new PageScroller(lv_navipt).init();
        //分页滚动示例代码>>>>>>>>>>>>>>>>>>>
        //示例代码>>>>>>>>>>>>>>>>>>>
    }

    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void onForwardClick(View v) {
        //top栏右边按钮响应

        toActivity(TopMenuWindow.createIntent(context, getResources().getStringArray(R.array.top_menu_navipt)), REQUEST_TO_TOP_MENU, false);
    }

    public void onSelectAll(View v) {
        selectAll(true);
    }

    public void onSelectAllNO(View v) {
        selectAll(false);
    }

    public void selectAll(boolean isSelected) {
        if (hashMap == null) {
            hashMap = new HashMap<Integer, Boolean>();
        }
        hashMap.clear();
        if (naviptlist != null) {
            for (int i = 0; i < naviptlist.size(); i++) {
                hashMap.put(i, isSelected);
            }
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }

        if (isSelected) {
            bt_navipt_do.setText(getString(R.string.delete));
        } else {
            bt_navipt_do.setText(getString(R.string.cancel));
        }

    }

    public void onDelSelected(View v) {
        boolean haveselected = false;
        for (int i = 0; i < mNaviptList.size(); i++) {
            if (hashMap.get(i)) {
                haveselected = true;
                break;
            }
        }

        if (haveselected) {
            new AlertDialog(context, getString(R.string.wxts), "确定删除选择的航点？", true, 0, this).show();
        } else {
            mIsEdit = false;
            findViewById(R.id.ctrl_navipt_edit).setVisibility(View.GONE);

            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        }

    }

    private void delSelected() {
        mIsEdit = false;
        findViewById(R.id.ctrl_navipt_edit).setVisibility(View.GONE);
        showShortToast(getString(R.string.deleteok));

        ArrayList<Long> pkIds = new ArrayList<Long>();

        for (int i = 0; i < mNaviptList.size(); i++) {
            if (hashMap.get(i)) {
                pkIds.add(mNaviptList.get(i).getId());
            }
        }
        DBDataCenter.getInstance().doDeleteWayPoint(pkIds);
        initData();
    }

    private void clearListData() {
        DBDataCenter.getInstance().doDeleteAllPoint();
        initData();
    }

    private void onToEdit() {
        if (naviptlist.size() < 1) {
            showShortToast(getString(R.string.tnotrackdelete));
            return;
        }
        mIsEdit = true;
        findViewById(R.id.ctrl_navipt_edit).setVisibility(View.VISIBLE);
        selectAll(false);
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    private final int REQUEST_TO_TOP_MENU = 30;
    private final int REQUEST_DETAIL = 31;
    private final int REQUEST_TO_EDIT_TEXT_INFO = 32;
    private final int SELECTICON = 43;
    private final int SELECTICON_DEL = 44;

    int _delIconIndex = -1;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == SELECTICON) {
            _iconIndex = resultCode;
            initData();
            return;
        }

        if (requestCode == SELECTICON_DEL) {
//            deleteWayptByIcon(resultCode);
            _delIconIndex = resultCode;
            if (_delIconIndex >=0 && _delIconIndex < WayPoint.TYPE_IDS.length) {
                int resId = WayPoint.TYPE_IDS[_delIconIndex];
                new AlertDialog(context, resId, "确认删除此图标的航点？", true, 11, this).show();
            }
            return;
        }


        if (resultCode == Msg.NAVI_TO_DEST) {
            setResult(resultCode);
            finish();
            return;
        }
        if (requestCode == REQUEST_DETAIL) {
            initData();
            return;
        }

        if (resultCode != RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case REQUEST_TO_EDIT_TEXT_INFO:
                mKey = "";
                if (data != null) {
                    mKey = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                }
                initData();
                break;
            case REQUEST_TO_TOP_MENU:
                if (data != null) {
                    switch (data.getIntExtra(TopMenuWindow.RESULT_POSITION, -1)) {
                        case 0:
                            _order = 1;
                            initData();
                            break;
                        case 1:
                            _order = 2;
                            initData();
                            break;
                        case 2:
                            _order = 0;
                            initData();
                            break;
                        case 3:
                            searchByIcon();
                            break;
                        case 4:
                            inputKeyword(true);
                            break;
                        case 5:
                            delByIcon();
                            break;
                        case 6:
                            onToEdit();
                            break;
                        case 7:
                            if (naviptlist.size() > 0) {
                                new AlertDialog(context, getString(R.string.wxts), getString(R.string.qdqkhd), true, 1, this).show();
                            } else {
                                showShortToast(getString(R.string.swjl));
                            }
                            break;
                        default:
                            break;
                    }
                }
                break;
        }
    }

    private void deleteWayptByIcon(int icon_num) {
        DBDataCenter.getInstance().doDeleteWayPointByIcon(icon_num);
        initData();
    }

    private void delByIcon() {
        toActivity(SelectIconActivity.createIntent(context, 0), SELECTICON_DEL);
    }

    private void searchByIcon() {
        toActivity(SelectIconActivity.createIntent(context, 0), SELECTICON);
    }

    String mKey = "";

    private void inputKeyword(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NICK
                    , getString(R.string.cxgjz), mKey, getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NICK
                    , getString(R.string.cxgjz), mKey);
        }

        toActivity(intent, REQUEST_TO_EDIT_TEXT_INFO, !toWindow);
    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }

        if (requestCode == 0) {
            delSelected();
        } else if (requestCode == 1) {
            clearListData();
        } else if (requestCode == 11) {
            deleteWayptByIcon(_delIconIndex);
        }
    }


    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Adapter
    public class DemoAdapter extends BaseAdapter<Entry<Integer, String>> {
        public DemoAdapter(Activity context) {
            super(context);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.navipt_view, parent, false);
            }

            ImageView iv_icon = BaseViewHolder.get(convertView, R.id.iv_icon);
            TextView tv_naviptname = BaseViewHolder.get(convertView, R.id.tv_naviptname);
            TextView tv_naviptdistance = BaseViewHolder.get(convertView, R.id.tv_naviptdistance);
            TextView tv_naviptdir = BaseViewHolder.get(convertView, R.id.tv_naviptdir);
            TextView tv_navipttime = BaseViewHolder.get(convertView, R.id.tv_navipttime);
            ImageView iv_pic = BaseViewHolder.get(convertView, R.id.iv_pic);
            iv_pic.setVisibility(View.GONE);
            TextView iv_check = BaseViewHolder.get(convertView, R.id.iv_check);
            iv_check.setTypeface(AppContext.getInstances().getIconfont());
            ImageView ivrtimg = BaseViewHolder.get(convertView, R.id.ivrtimg);

            final Entry<Integer, String> data = getItem(position);
            int index = data.getKey();
            if (index >= 0 && index < mNaviptList.size()) {
                WayPoint navipt = mNaviptList.get(index);
                iv_icon.setImageResource(navipt.getTypeIcon());
                tv_naviptname.setText(navipt.getName());
                if (navipt.getType() == 1) {
                    tv_naviptname.setTextColor(context.getResources().getColor(R.color.orangered));
                } else {
                    tv_naviptname.setTextColor(context.getResources().getColor(R.color.nhc_maintab_txt_normal));
                }
                LonLat llcar = SysUtils.getInstance().getLL();
                double distance = Start.getInstance().MapKit().getDistance(llcar, navipt.getLL());
                String DIS[] = SysUtils.getInstance().getDistanceStr((int) distance);
                tv_naviptdistance.setText(DIS[0] + DIS[1]);
                tv_naviptdir.setText(Start.getInstance().MapKit().getDirection(llcar, navipt.getLL()));
                tv_navipttime.setText(SysUtils.getInstance().getDateStr(navipt.getDatetime()));
                if (navipt.getPicurl().length() > 0) {
                    iv_pic.setVisibility(View.VISIBLE);
                }

                iv_check.setVisibility(View.GONE);
                if (mIsEdit) {
                    ivrtimg.setVisibility(View.GONE);
                    boolean isSelected = hashMap.get(index);
                    iv_check.setVisibility(View.VISIBLE);
                    if (isSelected) {
                        iv_check.setText(R.string.fonticon_xz);
                    } else {
                        iv_check.setText(R.string.fonticon_wxz);
                    }
                } else {
                    ivrtimg.setVisibility(View.VISIBLE);
                }
            }

            return super.getView(position, convertView, parent);
        }

        private final long serialVersionUID = 3L;

        @Override
        public long getItemId(int position) {
//            return getItem(position).getId();
            return serialVersionUID + position;
        }
    }

    LonLat _lastllcar;

    @Override
    protected void onResume() {
        super.onResume();
        TimeRefresher.getInstance().addTimeRefreshListener(TAG, 5000, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
    }

    @Override
    public void onTimerStart() {

    }

    @Override
    public void onTimerRefresh() {
        if (_isWorking) {
            return;
        }

        LonLat llcar = SysUtils.getInstance().getLL();
        if (_lastllcar != null) {
            double distance = Start.getInstance().MapKit().getDistance(llcar, _lastllcar);
            if (distance < 5) {
                return;
            }
        }
        _lastllcar = llcar;
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onTimerStop() {

    }


}
